/*
 * FileName:    　　　QueryUtils.java
 * Description:  Dateのパラメータ 変換
 * History:     2010-8-24 (廖宝俊) 1.0 Create
 */
package com.sn.system.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sn.system.common.constants.Constants;
import com.sn.system.common.validator.ValidatorUtils;

import org.apache.struts2.util.StrutsTypeConverter;


public class DateConverter extends StrutsTypeConverter {

    /**
     * StringからDateへ変換
     */
	public Object convertFromString(Map context, String[] values, Class toClass) {
        String dateString = null;
        if (values != null && values.length > 0) {
            dateString = values[0];
            if (dateString != null&&!dateString.equals("")) {
            	
            	 Pattern pattern;
     	        // System.out.println(expression);
     	        pattern = Pattern.compile(ValidatorUtils.DateExpression, 2);
     	        Matcher matcher = pattern.matcher(dateString.trim());
     	        if (!matcher.matches()) {
     	        	throw new RuntimeException();
     	        }
            	
                SimpleDateFormat format = Constants.DATE_FORMAT2;
                try {
                	Date date = format.parse(dateString.trim());
                	return date;
                } catch (ParseException e) {
                	try {
                		Date date=Constants.DATE_FORMAT6.parse(dateString.trim());
						return date;
					} catch (ParseException e1) {
					}
                }
            }
        }
        return null; 
	}

	/**
     * DateからStringへ変換
     */
	public String convertToString(Map context, Object obj) {
		 Date date = (Date) obj;
		 SimpleDateFormat format = Constants.DATE_FORMAT2;
	        String dateTimeString=format.format(date);
	        return dateTimeString;
	}

}
